﻿using System;
using System.Collections.Generic;
using System.Configuration;
using log4net.Repository.Hierarchy;

namespace Redis
{
    public enum CacheInstance
    {
        WEBSITE,
        OTHER
    }

    public class CacheFactory
    {
        private const string CACHETYPE = "CacheType";
        private const string CACHESTATUS = "IsEnableCache";
        private static Dictionary<CacheInstance, ICacheService> _dictCacheService = new Dictionary<CacheInstance, ICacheService>();
        private static object _lock = new object();

        public static ICacheService CreateInstance(CacheInstance cacheInstance)
        {
            bool isEnableCache;
            bool.TryParse(ConfigurationManager.AppSettings[CACHESTATUS], out isEnableCache);

            //Logger.Info(string.Format("[CacheFactory] CacheInstance: {0}, Enable: {1}", cacheInstance, isEnableCache));

            if (isEnableCache)
                try
                {
                    switch (ConfigurationManager.AppSettings[CACHETYPE])
                    {
                        case "NCache":
                            if (_dictCacheService.ContainsKey(cacheInstance) && _dictCacheService[cacheInstance] is NCacheService)
                                return _dictCacheService[cacheInstance];
                            lock (_lock)
                            {
                                var nCache = NCacheService.Instance();
                                _dictCacheService[cacheInstance] = nCache;
                                return nCache;
                            }
                       
                        default:
                            return null;
                    }

                }
                catch (Exception ex)
                {
                    ex.HelpLink += " [CacheFactory][CreateInstance]";
                    Logger.Error(ex);
                }

            return null;
        }
    }
}
